package com.joyson.app.module.home;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;

import com.joyson.app.R;
import com.joyson.app.common.ui.SimpleActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * @author joyson
 * @create 2018-10-26
 */
public class HomeActivity extends SimpleActivity {
    @BindView(R.id.viewpager_home)
    ViewPager viewPager;
    List<Fragment> fragmentList =new ArrayList<>();
    private HomeLeftFragment homeLeftFragment;
    private HomeRightFragment homeRightFragment;
    private static final int FRAGMENT_HOME_LEFT = 0;
    private static final int FRAGMENT_HOME_RIGHT = 1;
    private MyPagerAdapter adapter;
    @Override
    protected void initEventAndData() {
        homeLeftFragment = HomeLeftFragment.getInstance();
        homeRightFragment = HomeRightFragment.getInstance();
        //填充数据
        fragmentList.add(homeLeftFragment);
        fragmentList.add(homeRightFragment);

        adapter = new MyPagerAdapter(getSupportFragmentManager(),fragmentList);
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                showFragment(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_home;
    }

    private void showFragment(int index) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        hideFragment(ft);
        Fragment fragment = fragmentList.get(index);
        ft.show(fragment);
        ft.commit();
    }



    private void hideFragment(FragmentTransaction ft) {
        // 如果不为空，就先隐藏起来
        if (homeLeftFragment != null) {
            ft.hide(homeLeftFragment);
        }
        if (homeRightFragment != null) {
            ft.hide(homeRightFragment);
        }


    }
    public class MyPagerAdapter extends FragmentPagerAdapter {

        private List<Fragment> mfragmentList;

        public MyPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) {
            super(fm);
            this.mfragmentList = fragmentList;
        }

        @Override
        public Fragment getItem(int position) {
            return mfragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mfragmentList.size();
        }
    }

}
